package com.rxh.service;

import com.rxh.pojo.Result;
import com.rxh.pojo.core.CoreMerchantOrder;
import com.rxh.pojo.core.CoreMerchantOrderRmb;
import com.rxh.pojo.core.CoreOrder;
import com.rxh.pojo.core.CoreOrderChange;
import com.rxh.pojo.cross.BankResult;
import com.rxh.pojo.finance.FinanceBusinessMoney;
import com.rxh.utils.SystemConstant;
import com.rxh.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: 王德明
 * Date: 2018/10/22
 * Time: 9:46
 * Project: Management_new
 * Package: com.rxh.service
 */
@Service
public class RefundNotifyService {
    @Resource
    private TransactionService transactionService;
    @Resource
    private FinanceService financeService;
    private Logger logger = LoggerFactory.getLogger(getClass());

    public Result getResultMessage(BankResult bankResult) {
        Result result = new Result();
        //获取CoreOrder对象
        CoreOrder coreOrder = transactionService.getCoreOrderByOrderId(bankResult.getOrderId());
        //获取CoreOrderChange对象
        CoreOrderChange coreOrderChange = transactionService.getCoreOrderChangeById(bankResult.getOrderChangeId());
        //获取商户余额对象
        FinanceBusinessMoney financeBusinessMoney = financeService.getFinanceBusinessMoneyByRefId(coreOrder.getMerId());
        if (coreOrderChange.getStatus() == SystemConstant.REFUND_STATUS_BANK_PROCESSING) {
            if (bankResult.getStatus() == SystemConstant.CHANGE_BANK_STATUS_SUCCESS) {
                CoreMerchantOrder coreMerchantOrder = transactionService.getMerchantOrderByOrderId(coreOrder.getId());
                coreMerchantOrder.setSourceRefund(null == coreMerchantOrder.getSourceRefund() ? coreOrderChange.getAmount() : coreOrderChange.getAmount().add(coreMerchantOrder.getSourceRefund()));
                CoreMerchantOrderRmb coreMerchantOrderRmb = transactionService.getALLCoreMerchantOrderRmbById(coreOrder.getId());
                coreMerchantOrderRmb.setSourceRmbRefund(null == coreMerchantOrderRmb.getSourceRmbRefund() ? coreOrderChange.getRmbAmount() : coreOrderChange.getRmbAmount().add(coreMerchantOrderRmb.getSourceRmbRefund()));
                coreOrder.setExceptionStatus(coreOrderChange.getType());
                coreOrder.setExceptionAmount(coreMerchantOrder.getSourceRefund());
                coreOrder.setExceptionTime(new Date());
                coreOrder.setShipStatus(SystemConstant.SHIPPED);
                transactionService.updateByPrimaryKeySelectiveByOrderId(coreMerchantOrder);
                transactionService.updateCoreMerchantOrderRmb(coreMerchantOrderRmb);
                /**
                 * 通联通道退款异步通知可能生成新的退款ID
                 * 导致orderChange的id无法在通联退款查到对应的信息
                 */
                if (StringUtils.isNotBlank(bankResult.getBankRefundId())) {
                    transactionService.updateCoreMerchantOrderId(Long.parseLong(bankResult.getBankRefundId()), coreOrderChange.getId());
                }
                result.setCode(SystemConstant.UPDATE_SUCCESS);
                result.setMsg("退款信息更新成功!");
            } else {
                coreOrder.setExceptionStatus(SystemConstant.EXCEPTION_STATUS_NORMAL);
                coreOrderChange.setReasons(bankResult.getBankResult());
                rollbackFinanceBusinessMoney(coreOrderChange, financeBusinessMoney);
                result.setCode(SystemConstant.UPDATE_SUCCESS);
                result.setMsg("退款信息更新成功");
            }
            transactionService.updateCoreOrderByEntity(coreOrder);
            coreOrderChange.setStatus(bankResult.getStatus());
            coreOrderChange.setAuditTime(new Timestamp(System.currentTimeMillis()));
            transactionService.updateCoreOrderChangeByEntity(coreOrderChange);
            financeService.updateFinanceBusinessMoneyByPrimaryKeySelective(financeBusinessMoney);
        } else {
            result.setCode(SystemConstant.UPDATE_FAIL);
            result.setMsg("退款信息已更新");
        }
        return result;
    }

    /**
     * 回滚商户余额
     * （在审核成功时，admin后台已经将商户余额扣除，此时银行退款失败应恢复相应余额）
     *
     * @param coreOrderChange  订单变更对象
     * @param financeBusinessMoney 商户余额对象
     */
    private void rollbackFinanceBusinessMoney(CoreOrderChange coreOrderChange, FinanceBusinessMoney financeBusinessMoney) {
        if (null != financeBusinessMoney) {
            financeBusinessMoney.setUsableAmount(financeBusinessMoney.getUsableAmount()
                    .add(coreOrderChange.getRmbAmount())
                    .setScale(2, BigDecimal.ROUND_UP));
            financeBusinessMoney.setBookBalance(financeBusinessMoney.getBookBalance()
                    .add(coreOrderChange.getRmbAmount())
                    .setScale(2, BigDecimal.ROUND_UP));
            financeBusinessMoney.setRefundAmount(financeBusinessMoney.getRefundAmount()
                    .subtract(coreOrderChange.getRmbAmount())
                    .setScale(2, BigDecimal.ROUND_UP));
        }
    }
}
